from __future__ import absolute_import, division, print_function, unicode_literals

import datetime
from backtrader.feed import DataBase
from backtrader import date2num
from sqlalchemy import create_engine


class MySQLDataFeed(DataBase):
    def __init__(self, conn, load_data_sql):
        self.conn = conn
        self.load_data_sql = load_data_sql

    def start(self):       
        self.result = self.conn.query_sql(self.load_data_sql)

    def stop(self):
        # self.conn.close()
        # self.engine.dispose()
        pass

    def _load(self):
        one_row = self.result.fetchone()
        if one_row is None:
            return False
        self.lines.datetime[0] = date2num(one_row[0])
        self.lines.open[0] = float(one_row[1])
        self.lines.high[0] = float(one_row[2])
        self.lines.low[0] = float(one_row[3])
        self.lines.close[0] = float(one_row[4])
        self.lines.volume[0] = int(one_row[5])
        self.lines.openinterest[0] = -1
        return True


